﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Linq;
using System.Net.NetworkInformation;

namespace Device
{
    public class NetworkHelper
    {
        public static List<string> GetLocalIp4List()
        {
            List<string> Iplist = new List<string>();
            try
            {
                string hostName = Dns.GetHostName();
                foreach (var item in Dns.GetHostAddresses(hostName))
                {
                    if (item.AddressFamily == AddressFamily.InterNetwork)
                    {
                        Iplist.Add(item.ToString());
                    }
                }
                if (Iplist.Count > 0)
                {
                    return Iplist;
                }
                return Iplist;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex.Message}{ex.StackTrace}{ex.Source}");
                return Iplist;
            }

        }
        public static bool CheckPortIsEnable(int port)
        {
            try
            {
                IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
                if (ipGlobalProperties == null)
                    return false;
                IPEndPoint[] ipsUDP = ipGlobalProperties.GetActiveUdpListeners();
                if (ipsUDP == null || ipsUDP.Length == 0)
                    return false;
                var isPortUse = ipsUDP.FirstOrDefault(w => w.Port == port);
                if (isPortUse == null)
                    return true;
                else
                    return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex.Message}{ex.StackTrace}{ex.Source}");
                return false;
            }
        }
    }
}
